package cn.wolfcode.crm.web.filter;

import cn.wolfcode.crm.util.JSONResult;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

public class MyFormAuthenticationFilter extends FormAuthenticationFilter {
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        //配置响应会的数据的格式
        response.setContentType("application/json;charset=utf-8");
        //用ajax返回而不是 页面
        response.getWriter().print(JSON.toJSONString(new JSONResult()));

        //不放行去跳转别的页面
        return false;
    }

    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        String errorMsg="登录异常,请联系管理员";
        if (e != null) {
            /*表明e为UnknownAccountException的实例*/
            if (e instanceof UnknownAccountException) {
                errorMsg="用户名不存在";
            }else if (e instanceof IncorrectCredentialsException) {
                errorMsg="密码错误";
            }
        }
        response.setContentType("application/json;charset=utf-8");
        try {
            response.getWriter().print(JSON.toJSONString(new JSONResult(false,errorMsg)));
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        //有这句能在后台接收到报错类型,因此要把异常信息打印出来
        e.printStackTrace();
        return false;
    }
    //解决不能重复登陆的问题
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        //判断是否是登录的请求
        if(isLoginRequest(request, response)){
            //判断是否已经有用户登录过
            Subject subject = SecurityUtils.getSubject();
            if(subject.isAuthenticated()){
                //如果有就先注销掉
                subject.logout();
            }
        }
        return super.isAccessAllowed(request, response, mappedValue);
    }
}
